package com.xw.bo.ks.aspect;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author： XW -> ~
 * @create： 2024/6/6 16:23
 */
@Slf4j
@Aspect
@Component
public class ControllerLoggingAspect {

    @Resource
    private CacheControllerCodeInterface cacheControllerInfoService;

    @Pointcut("execution(* com.xw.bo.ks.controller..*.*(..))")
    public void controllerMethods() {
    }


    @Around("controllerMethods()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();

        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();
        log.info("请求开始, 各个参数, url: {}, method: {}, uri: {}, params: {}", url, method, uri, queryString);
        String key = "cache:uri_" + uri + "_params_" + queryString;

        if (cacheControllerInfoService.isCache(uri)) {
            Object object = cacheControllerInfoService.backResult(key);
            if (null != object) {
                return object;
            }
        }

        // result的值就是被拦截方法的返回值
        Object result = pjp.proceed();
        log.info("请求结束，controller的返回值是 " + JSON.toJSONString(result));

        if (cacheControllerInfoService.isCache(uri)) {
            cacheControllerInfoService.saveResult(uri, key, result);
        }
        return result;
    }


}
